<!--  -->
<template>
  <el-drawer v-model="drawerFlag" direction="rtl" @closed="handleClosed">
    <template #header>Roles</template>
    <template #default>
      <el-form :model="formModel" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="角色" prop="role_name">
          <el-input v-model="formModel.role_name"></el-input>
        </el-form-item>
        <el-form-item label="菜单列表" prop="role_description">
          <template v-for="item in menuListOptions" :key="item.menu_id">
            <el-divider content-position="left">
              <el-checkbox :model-value="isParentChecked(item.menu_id)" :indeterminate="isParentIndeterminate(item.menu_id)" @change="handleParentCheck(item.menu_id, $event)" :label="item.menu_title" :value="item.menu_id" />
            </el-divider>
            <div class="checkbox-group">
              <el-checkbox-group v-model="menuListValue">
                <el-checkbox v-for="item2 in item.children" :key="item2.menu_id" :label="item2.menu_title" :value="item2.menu_id" />
              </el-checkbox-group>
            </div>
          </template>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleClickBtnCancel">取消</el-button>
        <el-button type="primary" @click="handleClickBtnSubmit">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { ref, reactive, defineEmits } from 'vue'
import Dal from '@/dal'
import { ElMessage } from 'element-plus'
import type { ElForm } from 'element-plus'

const drawerFlag = ref(false)

const menuListOptions = ref<any[]>([])
const menuListValue = ref<any>([])

const emits = defineEmits(['close', 'submit'])

const formRef = ref<InstanceType<typeof ElForm>>()

const formModel = reactive({
  role_id: 0,
  role_name: '',
  role_description: '',
})
const rules = reactive({
  role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
})

const handleClickBtnCancel = () => {
  formRef.value?.resetFields()
  drawerFlag.value = false
}

const handleClickBtnSubmit = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      // 这里可以添加提交表单数据到后端的逻辑
      await Dal.RolesMenuRelations.deleteByRoleId(formModel.role_id)
      const reqs: any[] = []
      menuListValue.value.forEach((val: any) => {
        reqs.push(
          Dal.RolesMenuRelations.save({
            role_id: formModel.role_id,
            menu_id: val,
          })
        )
      })
      await Promise.all(reqs)
      ElMessage({
        message: '提交成功',
        type: 'success',
      })
      emits('submit', { ...formModel })
    } else {
      console.log('表单验证失败')
    }
  })

  drawerFlag.value = false
}

const open = async (val: any, menuIds: any[]) => {
  await getMenuDataList()
  if (val) {
    formModel.role_id = val.role_id
    formModel.role_name = val.role_name
    menuListValue.value = menuIds
  }
  drawerFlag.value = true
}

const getMenuDataList = async () => {
  const res = await Dal.Menus.findTree()
  console.log(res)
  menuListOptions.value = res.data
}
const handleClosed = async () => {
  menuListValue.value = []
  emits('close')
}
// 判断父级复选框是否选中
const isParentChecked = (parentId: number) => {
  const childIds = menuListOptions.value.find((item) => item.menu_id === parentId)?.children?.map((child: any) => child.menu_id) || []
  return childIds.every((id: any) => menuListValue.value.includes(id))
}

// 判断父级复选框是否为部分选中
const isParentIndeterminate = (parentId: number) => {
  const childIds = menuListOptions.value.find((item) => item.menu_id === parentId)?.children?.map((child: any) => child.menu_id) || []
  const selectedCount = childIds.filter((id: any) => menuListValue.value.includes(id)).length
  return selectedCount > 0 && selectedCount < childIds.length
}

// 父级复选框点击事件
const handleParentCheck = (parentId: number, checked: boolean) => {
  const childIds = menuListOptions.value.find((item) => item.menu_id === parentId)?.children?.map((child: any) => child.menu_id) || []
  if (checked) {
    // 全选
    menuListValue.value = Array.from(new Set([...menuListValue.value, ...childIds]))
  } else {
    // 全不选
    menuListValue.value = menuListValue.value.filter((id: any) => !childIds.includes(id))
  }
}

defineExpose({
  open,
})
</script>
<style lang="scss" scoped>
.checkbox-group {
  width: 100%;
}
</style>
